package ui.user;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import ui.admin.staff.*;
import hibernate.dao.CourseDAO;
import hibernate.dao.StaffDAO;
import hibernate.entity.Accounts;
import hibernate.entity.Courses;
import hibernate.entity.Staffs;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;
import org.primefaces.event.TransferEvent;
import org.primefaces.model.DualListModel;
import ui.admin.AbstractAdminBean;
import ui.common.AbstractUIBean;
import util.Converter;
import util.Md5Generator;
import util.RandomGenerator;

//import util.UploadBean;
/**
 * c
 *
 * @author QuynhDu
 */
@ManagedBean
@RequestScoped
public class UserStaffManager extends AbstractAdminBean {

    StaffDAO sDAO = new StaffDAO();
    private Accounts currAcc = new Accounts();
    private String username;
    private String password;
    private String email;
    private String fullname;
    private String address;
    private String Staffimage;
    private boolean gender;
//    UploadBean uploadBean = new UploadBean();
    List<Courses> sourceCourse,
            targetCourse;
    DualListModel<Courses> dualCourse = new DualListModel<Courses>();
    CourseDAO cDao = new CourseDAO();
    Date birthday;
    @NotNull
    String phone;
    List<Staffs> allStaff;

    public UserStaffManager() {
        sourceCourse = new ArrayList<Courses>();
        targetCourse = new ArrayList<Courses>();
        allStaff = new StaffDAO().readLiving();
    }

    public List<Courses> getAvaiCourse() {
        return sourceCourse;
    }

    public void setAvaiCourse(List<Courses> avaiCourse) {
        this.sourceCourse = avaiCourse;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    /**
     * @return the currAcc
     */
    public Accounts getCurrAcc() {
        return currAcc;
    }

    /**
     * @param currAcc the currAcc to set
     */
    public void setCurrAcc(Accounts currAcc) {
        this.currAcc = currAcc;
    }

    /**
     * @return the username
     */
    public String getUsername() {
        return username;
    }

    /**
     * @param username the username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

//    public UploadBean getUploadBean() {
//        return uploadBean;
//    }
//
//    public void setUploadBean(UploadBean uploadBean) {
//        this.uploadBean = uploadBean;
//    }
    /**
     * @return the fullname
     */
    public String getFullname() {
        return fullname;
    }

    /**
     * @param fullname the fullname to set
     */
    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    /**
     * @return the address
     */
    public String getAddress() {
        return address;
    }

    /**
     * @param address the address to set
     */
    public void setAddress(String address) {
        this.address = address;
    }

    /**
     * @return the Staffimage
     */
    public String getStaffimage() {
        return Staffimage;
    }

    /**
     * @param Staffimage the Staffimage to set
     */
    public void setStaffimage(String Staffimage) {
        this.Staffimage = Staffimage;
    }

    public DualListModel<Courses> getDualCourse() {
        return dualCourse;
    }

    public void setDualCourse(DualListModel<Courses> dualCourse) {
        this.dualCourse = dualCourse;
    }

    public boolean isGender() {
        return gender;
    }

    public void setGender(boolean gender) {
        this.gender = gender;
    }

    public List<Courses> getSourceCourse() {
        return sourceCourse;
    }

    public void setSourceCourse(List<Courses> sourceCourse) {
        this.sourceCourse = sourceCourse;
    }

    public List<Courses> getTargetCourse() {
        return targetCourse;
    }

    public void setTargetCourse(List<Courses> targetCourse) {
        this.targetCourse = targetCourse;
    }

    /**
     * @param Staffs
     * @return String
     * @see edit page with the fields to modify
     */
    public String edit(Staffs staff) {
        currAcc = staff.getAccounts();
        username = currAcc.getUserName();
        password = currAcc.getPassword();
        address = currAcc.getAddress();
        fullname = currAcc.getFullName();
        email = currAcc.getEmail();
        birthday = currAcc.getBirthday();
        phone = staff.getPhone();
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        session.setAttribute("editStaff", staff);
        return "edit";
    }

    /**
     * @return String
     * @see list page of staff with a staff updated some fields
     */
    public String doupdate() {
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        Staffs st = (Staffs) session.getAttribute("editStaff");
        currAcc = st.getAccounts();
        currAcc.setUserName(username);
        currAcc.setBirthday(birthday);
        currAcc.setAddress(address);
        currAcc.setFullName(fullname);
        currAcc.setEmail(email);
        currAcc.setBirthday(birthday);
        try {
            hbTransaction = hbSession.beginTransaction();
            currAcc = (Accounts) hbSession.merge(currAcc);
            hbSession.update(currAcc);
            st.setAccounts(currAcc);
            st.setPhone(phone.trim());
            st = (Staffs) hbSession.merge(st);
            hbSession.update(st);
            hbTransaction.commit();
            showPrimeMessage("Success", "Staff " + st.getStaffId() + " updated");
            allStaff = new StaffDAO().readLiving();
            return "list?faces-redirect=true";
        } catch (Exception e) {
            hbTransaction.rollback();
            showPrimeMessage("Error", "Unexpected error! update fail");
        }

        return null;
    }

    /**
     * @return String
     * @see list page with the added staff
     */
    public String docreate() {
        try {
            hbTransaction = hbSession.beginTransaction();
            currAcc = new Accounts(username, email, fullname, address, "a", birthday, gender);
            if (!checkUserNameEmailAvailble(username, email)) {
                return "create";
            }
            currAcc.setStatus(0);
            currAcc.setImage("empty");
            String p = RandomGenerator.randomString();
            p = "staff";
            String hash = Md5Generator.getMd5(p);
            currAcc.setPassword(hash);
            currAcc.setRoleId(2);
            hbSession.save(currAcc);
            Staffs st = new Staffs();
            st.setAccounts(currAcc);
            st.setPhone(phone);

            st.setStatus(1);
            hbSession.save(st);
            hbTransaction.commit();
            allStaff = new StaffDAO().readLiving();
            return "list?faces-redirect=true";
        } catch (Exception e) {
            hbTransaction.rollback();
        }
        return null;
    }

    /**
     * @param Staffs
     * @return String
     * @see pick course page
     */
    public String pickCourse(Staffs s) {

        sourceCourse = new CourseDAO().readAll();
        targetCourse = Converter.iteratorToList(s.getCourseses().iterator());
        for (Courses courses : targetCourse) {
            sourceCourse.remove(courses);
        }
        dualCourse = new DualListModel<Courses>(sourceCourse, targetCourse);
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        session.setAttribute("editStaff", s);
        getHttpSession().removeAttribute("courses");
        return "pickcourse";
    }

    /**
     * @param TransferEvent an event to choose a course for staff
     * @return void
     */
    public void courseTransfer(TransferEvent event) {
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        targetCourse = (List<Courses>) session.getAttribute("courses");
        if (targetCourse == null) {
            targetCourse = new ArrayList<Courses>();
        }

        for (Object item : event.getItems()) {
            int id = Integer.parseInt(item.toString());
            boolean exist = false;
            for (Courses courses : targetCourse) {
                if (courses.getCourseId() == id) {
                    exist = true;
                }
            }
            if (!exist) {
                Courses c = cDao.readByID(id);
                targetCourse.add(c);
            }

            showPrimeMessage("Result", String.valueOf(targetCourse.size()));
        }
        session.setAttribute("courses", targetCourse);
    }

    /**
     * @return String
     * @see list page after the chosen course for the staff is updated
     */
    public String updateCourses() {
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        targetCourse = (List<Courses>) session.getAttribute("courses");
        Staffs stu = (Staffs) session.getAttribute("editStaff");
        hbTransaction = hbSession.beginTransaction();
        try {
            for (Courses courses : targetCourse) {
                courses.getStaffses().add(stu);
                courses = (Courses) hbSession.merge(courses);
                hbSession.update(courses);
            }
            stu = (Staffs) hbSession.merge(stu);
            hbSession.update(stu);
            hbTransaction.commit();
        } catch (Exception e) {
            hbTransaction.rollback();
        }
        showPrimeMessage("Success", "Updated");
        return "list";
    }

    /**
     * @param Staffs a staff for removing from the system
     * @return void
     * @see list page
     */
    public void remove(Staffs stu) {

        if (sDAO.remove(stu) > 0) {
            allStaff = new StaffDAO().readLiving();
            showPrimeMessage("Success", "Course " + stu.getStaffId() + " has been removed");
        }
    }

    /**
     * @param Staffs a staff for viewing his all info in details
     * @return String
     * @see staffdetail page
     */
    public String viewDetail(Staffs s) {
        HttpSession session = getHttpSession();
        session.setAttribute("viewStaff", s);
        return "admin-staff-detail";
    }

    /**
     * @return List<Staffs>
     * @see a whole list of staffs
     */
    public List<Staffs> getAllStaff() {
        return allStaff;
    }
}
